package com.ztools.wx.job;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.ztools.api.service.pc.PcPayService;
import com.ztools.common.model.wx.payment.Cart;
import com.ztools.common.util.common.RedisHelper;
import com.ztools.common.util.common.Result;
import com.ztools.common.util.common.ResultCode;
import net.javacrumbs.shedlock.spring.annotation.SchedulerLock;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.atomic.AtomicInteger;

import static com.ztools.common.util.wx.RedisUtil.CART_TO_SEND_KEY_PREFIX;

/**
 * @Author: seeTools
 * @Date: 2023/6/4  10:49
 * @Version 1.0
 */
@Component
public class PaymentJob {

    private static final int MAX_TIMES = 10;
    private final Logger logger = LoggerFactory.getLogger(getClass());
    @Resource
    private RedisHelper redisHelper;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private PcPayService pcPayService;

    @Scheduled(fixedDelay = 2000)
    @SchedulerLock(name = "submitCartJob", lockAtLeastFor = "2s")
    public void submitCartJob() {
        // 查询待保存的队列，一次最多保存10条记录，返回失败的不算
        AtomicInteger times = new AtomicInteger();
        String pattern = CART_TO_SEND_KEY_PREFIX + "*";
        redisHelper.scan(pattern, item -> {
            String key = new String(item, StandardCharsets.UTF_8);
            if (StrUtil.isNotEmpty(key) && times.get() <= MAX_TIMES) {
                String paymentNo = key.split(CART_TO_SEND_KEY_PREFIX)[1];
                // 判断该笔订单是否处于保存中的状态
                String savingRedisKey = "cache:cart:saving:" + paymentNo;
                Boolean hasKey = stringRedisTemplate.hasKey(savingRedisKey);
                if (hasKey != null && !hasKey) {
                    String cartStr = stringRedisTemplate.opsForValue().get(key);
                    if (StrUtil.isNotEmpty(cartStr) && JSONUtil.isJson(cartStr)) {
                        Cart cart = JSONUtil.toBean(cartStr, Cart.class);
                        Result result = pcPayService.save(cart);
                        if (ResultCode.SUCCESS.getCode() == result.getCode()) {
                            times.getAndIncrement();
                            // 移除待保存记录
                            stringRedisTemplate.delete(key);
                        }
                    }
                }
            }
        });
    }
}
